import axios from 'axios'

const $http = axios.create({
  timeout: 30000,
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
    'Cache-Control': 'no-cache',
    'Pragma': 'no-cache'
  }
})

$http.configObj = {};

$http.config = function(config){
  let defaultConfig = {
    hiddenHttpMethod: false
  };
  $http.configObj = Object.assign(defaultConfig, config);
}


// 在实例上去修改拦截器, 避免污染了全局的axios

$http.interceptors.request.use(function (config) {
  if ($http.configObj.hiddenHttpMethod) {
    let requestMethod = config.method
    if (requestMethod === 'delete' || requestMethod === 'put' || requestMethod === 'patch') {
      config.method = 'post';
    }
    config.headers['X-HTTP-METHOD-Override'] = requestMethod;
    return config;
  } else {
    return config;
  }
}, function (error) {
  return Promise.reject(error);
});

$http.interceptors.response.use(function (response) {
  return response.data
}, function (error) {
  const response = error.response
  // ------------以下代码为了之前的兼容性暂时保留, 后续将在大版本的更新中删除-------------
  if (response) {
    response.code = response.data.code
    response.message = response.data.message
  }
  // ------------以上代码为了之前的兼容性暂时保留, 后续将在大版本的更新将删除-------------
  return response ? Promise.reject(response) : Promise.reject(error) // 修改客户端引起的错误response为undefined导致报错问题
})
if (typeof window !== 'undefined') {
window.$http = $http
} else {
  global.$http = $http
}
export default $http
